#include <unistd.h>
#include <string>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <thread>
#define DEFAULT_PORT 8888
using namespace std;
void Handle(int fd,struct sockaddr_in addr)
{
    //服务器使用多线程来处理客户端请求
    while(1)
{
    char buff[1024];
    //cout<<"等待读取"<<endl;
    int n=read(fd,buff,sizeof(buff)-1);
    if(n>0)
    {
        buff[n]='\0';
        cout<<"IP:"<<inet_ntoa(addr.sin_addr)<<",port:"<<ntohs(addr.sin_port)<<"Request:"<<buff<<endl;
    }
    else if(n==0)
    {
        cout<<"写端关闭"<<endl;
        break;
    }
    else if(n==-1)
    {
        cout<<"读取错误"<<endl;
        break;
    }
}
}

int main(int argc,char* argv[],char* envp[])
{
    //1.创建套接字
    int sock=socket(AF_INET,SOCK_STREAM,0);
   cout<<sock<<endl;
    struct sockaddr_in local;
    memset(&local,0,sizeof(local));
    local.sin_port=htons(DEFAULT_PORT);
    local.sin_addr.s_addr=INADDR_ANY;
    local.sin_family=AF_INET;
    //2.绑定
    int retb=bind(sock,(sockaddr*)&local,sizeof(local));
    if(retb<0)
    {
        cout<<"bind error"<<endl;
        exit(-2);
    }
    //3.监听
    int listensock=listen(sock,5);
    if(listensock<0)
    {
        cout<<"listen error"<<endl;
        exit(-1);
    }
    struct sockaddr_in client;
    socklen_t len;
    while(1)
    {
        //4.等待客户端发送
        int n=accept(sock,(sockaddr*)&client,&len);
        cout<<n<<endl;
        if(n<0)
        {
            cout<<"等待链接"<<endl;
            continue;
        }
        cout<<"链接成功"<<endl;
        thread t(Handle,n,client);
        t.detach();
    }   
        return 0;
}
